package com.glela.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.glela.common.constant.BaseConstants;
import com.glela.constant.BizConstant;
import com.glela.goods.model.request.GoodsRequest;
import com.glela.goods.model.request.SearchRequest;
import com.glela.goods.model.vo.brand.BrandVo;
import com.glela.goods.model.vo.goods.GoodsESVo;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.model.vo.goods.GoodsSimpleVo;
import com.glela.goods.service.BrandService;
import com.glela.goods.service.GoodsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

/**
 * 校妆APP搜索
 * 
 * @author 卫耀华
 *
 */
@RequestMapping("/search")
@RestController
public class SearchController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(SearchController.class);

	@Autowired
	private BrandService brandService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserService userService;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;

	/**
	 * 校妆APP获取热搜词
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getHotSearchWords", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getHotSearchWords(@RequestBody GoodsRequest request) {
		try {
			if ((BizConstant.SEARCH_TYPE_GOODS != request.getType())
					&& (BizConstant.SEARCH_TYPE_BRAND != request.getType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			if (BizConstant.SEARCH_TYPE_GOODS == request.getType()) {
				List<String> list = goodsService.getHotSearchWords();
				return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
			} else if (BizConstant.SEARCH_TYPE_BRAND == request.getType()) {
				List<String> list = brandService.getHotSearchWords();
				return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 校妆APP搜索（elasticsearch搜索）
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/esSearch", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> esSearch(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getSearchKeyWord())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String searchKeyWord = request.getSearchKeyWord();
			if ((BizConstant.SEARCH_TYPE_GOODS != request.getType())
					&& (BizConstant.SEARCH_TYPE_BRAND != request.getType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			int roleId = 0;
			if (request.getUserId() != null && request.getUserId() > 0L) {
				User user = userService.getUser(request.getUserId());
				if (user != null) {
					roleId = user.getRoleId();
				}
			}
			if (BizConstant.SEARCH_TYPE_GOODS == request.getType()) {
				if ((0 != request.getGoodsType()) && (1 != request.getGoodsType())) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
				}
				logger.info("---搜索商品开始---");
				List<GoodsSimpleVo> list = goodsService.esSearchGoods(request.getGoodsType(), roleId, searchKeyWord,
						request.getStartIndex(), request.getPageSize());
				int count = goodsService.esSearchGoodsCount(request.getGoodsType(), searchKeyWord);
				return new ResponseEntity<>(new ResponseResultModel<>(
						new ResponsePageModel<GoodsSimpleVo>(count, request.getPageSize(), request.getPageNum(), list)),
						HttpStatus.OK);
			} else if (BizConstant.SEARCH_TYPE_BRAND == request.getType()) {
				logger.info("---搜索品牌开始---");
				List<BrandVo> list = brandService.esSearchBrand(request.getSearchKeyWord(), request.getStartIndex(),
						request.getPageSize());
				return new ResponseEntity<>(
						new ResponseResultModel<>(
								new ResponsePageModel<BrandVo>(0, request.getPageSize(), request.getPageNum(), list)),
						HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29905), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("ES搜索异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/syncGoodsCToES", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> syncGoodsCToES(@RequestBody GoodsRequest request) {
		goodsService.syncGoodsCToES();
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	@RequestMapping(value = "/syncGoodsBToES", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> syncGoodsBToES(@RequestBody GoodsRequest request) {
		goodsService.syncGoodsBToES();
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	@RequestMapping(value = "/syncBrandToES", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> syncBrandToES(@RequestBody GoodsRequest request) {
		goodsService.syncBrandToES();
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}
	
	/**
	 * 
	* **********************************************
	* @Title: esGlobalSearch
	* @Description: es全局搜索
	* @param @param request
	* @param @return    设定文件
	* @return ResponseEntity<?>    返回类型
	* @throws		异常
	* @author NingChongQing		作者
	* @date 2017年7月21日 上午9:04:58		时间
	* **********************************************
	 */
	@RequestMapping(value = "/esGlobalSearch", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> esGlobalSearch(@RequestBody GoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getSearchKeyWord())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String searchKeyWord = request.getSearchKeyWord();
			//店主用户ID  默认校妆姐姐店铺的店主ID
			//店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
			User user = null;
			if (!ParameterUtils.validParams(request.getUserId())) {
				user = this.userService.getUserById(request.getUserId());
				User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
				storeUserId = storeUser.getId().intValue();
			}
			if ((BizConstant.SEARCH_TYPE_GOODS != request.getType())
					&& (BizConstant.SEARCH_TYPE_BRAND != request.getType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			if (BizConstant.SEARCH_TYPE_GOODS == request.getType()) {
				logger.info("---全局搜索商品开始---");
				List<GoodsESVo> list = goodsService.esGlobalSearchGoods(storeUserId, searchKeyWord,
						request.getStartIndex(), request.getPageSize(),user);
				int count = list == null ? 0 : list.size();
				return new ResponseEntity<>(new ResponseResultModel<>(
						new ResponsePageModel<GoodsESVo>(count, request.getPageSize(), request.getPageNum(), list)),
						HttpStatus.OK);
			} else if (BizConstant.SEARCH_TYPE_BRAND == request.getType()) {
				logger.info("---全局搜索品牌开始---");
				List<BrandVo> list = brandService.esSearchBrand(request.getSearchKeyWord(), request.getStartIndex(),
						request.getPageSize());
				return new ResponseEntity<>(
						new ResponseResultModel<>(
								new ResponsePageModel<BrandVo>(0, request.getPageSize(), request.getPageNum(), list)),
						HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29905), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("ES全局搜索异常 ,错误信息: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* **********************************************
	* @Title: initSearch 
	* @Description: 搜索初始化接口
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月12日 下午3:49:51 
	* **********************************************
	 */
	@RequestMapping(value = "/initSearch", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> initSearch(@RequestBody SearchRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if ((BizConstant.SEARCH_TYPE_GOODS != request.getType())
					&& (BizConstant.SEARCH_TYPE_BRAND != request.getType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			tempKey = StringUtils.EMPTY + request.getType();
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				Map<String, Object> initMap = new HashMap<String, Object>();
				String initializeWord = "";// 默认搜索关键字
				List<String> whatYouWant = new ArrayList<String>();// 猜你所想
				if (BizConstant.SEARCH_TYPE_GOODS == request.getType()) {// 商品搜索
					try {
						initializeWord = this.baseRestrictionsService.getBaseRestrictionsForCache("search_good_word").getName();
					} catch (Exception e) {
					}
					try {
						String searchThinkWords = this.baseRestrictionsService.getBaseRestrictionsForCache("search_think_words").getName();
						String [] searchWordsArr = searchThinkWords.split("\\|");
						if (searchWordsArr.length > 0) {
							for (String words : searchWordsArr) {
								whatYouWant.add(words);
							}
						}
					} catch (Exception e) {
					}
				} else if (BizConstant.SEARCH_TYPE_BRAND == request.getType()) {// 品牌搜索
					try {
						initializeWord = this.baseRestrictionsService.getBaseRestrictionsForCache("search_brand_word").getName();
					} catch (Exception e) {
					}
				}
				initMap.put("initializeWord", initializeWord);
				initMap.put("whatYouWant", whatYouWant);
				rslt = toResultModelJSON(initMap);
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error("搜索初始化接口异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 1800));
	}
	
	/**
	* **********************************************
	* @Title: newEsSearch 
	* @Description: 新ES商品搜索
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月14日 下午3:37:49 
	* **********************************************
	 */
	@RequestMapping(value = "/newGoodsEsSearch", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> newGoodsEsSearch(@RequestBody GoodsRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getSearchKeyWord(),request.getPageNum(),request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String searchKeyWord = request.getSearchKeyWord();
			// 统计搜索词汇
			this.goodsService.statisticsGoodsSearchWords(searchKeyWord);
			//店主用户ID
			Integer xzJJUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
			// 店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = xzJJUserId;
			//登录人信息
			if (!ParameterUtils.validParams(request.getUserId())) {
				User user = this.userService.getUserById(request.getUserId());
				User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
				storeUserId = storeUser.getId().intValue();
			}
			// 角色  默认为校妆姐姐
			String role = "MAJOR";
			if (storeUserId.intValue() != xzJJUserId.intValue()) {
				role = "GENERAL";
			}
			tempKey = StringUtils.EMPTY + role + "-" + searchKeyWord + "-" + request.getPageNum() + "-" + request.getPageSize();
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<GoodsListResponse> list = this.goodsService.newGoodsEsSearchGoods(storeUserId, searchKeyWord,request.getStartIndex(), request.getPageSize());
				rslt = toResultModelJSON(new ResponsePageModel<GoodsListResponse>(list.size(), request.getPageSize(), request.getPageNum(), list));
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error("新ES全局搜索异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 120));
	}
}
